package org.hishenframework.core.data.jdbc.template;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.jdbc.core.JdbcTemplate;

public class HishenSimpleJdbcUpdate {
	
	private String tableName;
	private List<String> generatedKeyColumns;
	private JdbcTemplate jdbcTemplate;
	
	public HishenSimpleJdbcUpdate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public HishenSimpleJdbcUpdate withTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}
	
	public HishenSimpleJdbcUpdate usingGeneratedKeyColumns(String... columnNames) {
		generatedKeyColumns = Arrays.asList(columnNames);
		return this;
	}
	
	public HishenSimpleJdbcUpdate usingGeneratedKeyColumns(List<String> columnNames) {
		generatedKeyColumns = columnNames;
		return this;
	}
	
	public int execute(Map<String, Object> args) {
		StringBuilder startSql = new StringBuilder("UPDATE ");
		startSql.append(tableName).append(" SET ");
		StringBuilder endSql = new StringBuilder(" WHERE ");
		List<Object> beginParams = new ArrayList<>();
		List<Object> endParams = new ArrayList<>();
		for (Entry<String, Object> entry : args.entrySet()) {
			if (!generatedKeyColumns.contains(entry.getKey())) {
				startSql.append(entry.getKey()).append(" = ?, ");
				beginParams.add(entry.getValue());
			} else {
				endSql.append(entry.getKey()).append(" = ? AND ");
				endParams.add(entry.getValue());
			}
		}
		startSql.delete(startSql.length() - 2, startSql.length());
		endSql.delete(endSql.length() - 5, endSql.length());
		startSql.append(endSql);
		
		beginParams.addAll(endParams);
		int count = jdbcTemplate.update(startSql.toString(), 
						beginParams.toArray(new Object[beginParams.size()])
					);
		return count;
	}
	
	 
}
